<?php
namespace app\common\controller;
use app\common\controller\Base;
use think\Request;
/**
 * admin 基类控制器
 */
class Common extends Base{
    public function __construct(){
        parent::__construct();
        header("Content-type:text/html;charset=utf-8");

    }
    /**
     * 通过url获取数据
     * @param String $url
     * @param String charset 将获取的数据转换成该字符编码
     * @param Number $maxnum 尝试连接的次数
     * @param Array $options curl的option设置
     */

    private function data_from_url($url, $options = array(), $charset = 'utf-8', $maxnum = 5)
    {
//        include('D:\sofwear\PHPstorm\PhpStorm 2016.2\plugins\php\lib\php.jar!\com\jetbrains\php\lang\psi\stubs\data\fileinfo.php');
        set_time_limit(40);
        $cp = curl_init();
        $opt = array(
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            //CURLOPT_ENCODING => 'gzip',

            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36'
        );

        curl_setopt_array($cp, $opt);
        if ($options) {
            curl_setopt_array($cp, $options);
        }

        $_arr = parse_url($url);
        if (!empty($_arr['scheme']) && $_arr['scheme'] == 'https') {
            curl_setopt($cp, CURLOPT_SSL_VERIFYPEER, false);
        }
        $start_time = date('Y-m-d H:i:s');
        $contents = curl_exec($cp);
        $num = 1;
        while (curl_errno($cp) === 28) {
            if ($num > $maxnum) {
                break;
            }
            $num++;
            $start_time = date('Y-m-d H:i:s');
            $contents = curl_exec($cp);
        }
        $errno = curl_errno($cp);
        $error = curl_error($cp);
        $content_type = curl_getinfo($cp, CURLINFO_CONTENT_TYPE);
        $chear_type = strrchr($content_type, '=');

        $chear_type = trim($chear_type, ' =');
        //file_put_contents('post.txt', date('Y-m-d H:i:s  ') . $url . PHP_EOL . var_export(curl_getinfo($cp),true) . PHP_EOL . PHP_EOL, FILE_APPEND);
        curl_close($cp);
        if (!$error) {
            $fo = finfo_open(FILEINFO_MIME_TYPE);
            if (strtolower(strstr(finfo_buffer($fo, $contents), '/', true)) == 'text') { //如果是文本则进行转码  否则不转码
                if ($charset) {
                    //$chear_type = strtolower(mb_detect_encoding($contents,'gbk,gb2312,ASCII,UCS-2,UCS-2LE,UCS-2BE,'.$charset));
                    if ($chear_type) {
                        if ($chear_type != $charset) {
                            $contents = mb_convert_encoding($contents, $charset, $chear_type);
                            // $contents=thbmsz($contents,$charset);
                            $contents = preg_replace('/charset\=".*?"/', $charset, $contents);
                        }
                    }
                }
            }
        } else {
            $contents = '';
        }
        file_put_contents('test.txt', $start_time . '--' . date('Y-m-d H:i:s  ') . $url . PHP_EOL . $contents . PHP_EOL . PHP_EOL, FILE_APPEND);
        return array('contents' => $contents, 'error' => $error, 'errno' => $errno);
    }
    /**
     * 将请求参数放到url上
     * @param String $url
     * @param String or Array $param 参数
     */
    private function set_url_param($url, $param = array())
    {
        $p = '';

        if (is_array($param)) {
            foreach ($param as $k => $v) {
                $p .= "{$k}=" . urlencode($v) . "&";
            }
            $p = trim($p, '&');
        } else if (is_string($param)) {
            $p .= $param;
        }

        $uinfo = parse_url($url);
        $new_url = '';
        !empty($uinfo['scheme']) && $new_url .= $uinfo['scheme'] . '://';
        !empty($uinfo['host']) && $new_url .= $uinfo['host'];
        !empty($uinfo['port']) && $new_url .= ':' . $uinfo['port'];
        !empty($uinfo['path']) && $new_url .= $uinfo['path'];

        $query = '';
        if (!empty($uinfo['query'])) {
            $query .= '?' . $uinfo['query'];
        }
        if ($p) {
            if ($query) {
                $query .= '&' . $p;
            } else {
                $query .= '?' . $p;
            }
        }
        $new_url .= $query;

        !empty($uinfo['fragment']) && $new_url .= '#' . $uinfo['fragment'];
        return $new_url;
    }
    /**
     * get方式 获取数据
     * @param String $url
     * @param $param 字符串 或 数组
     */
    private function get_interface($url, $param = array())
    {
        $opt[CURLOPT_HTTPGET] = true;
        $url = $this->set_url_param($url, $param);
        //echo $url;exit;
        return $this->data_from_url($url, $opt);
    }
    /**
     * 远程获取数据(周园园)
     * @param String $url
     * @param String or Array $param 参数
     * @param int $type 0 get ; 1 post
     */
    /*
   protected function get_data_url($url, $param = array(), $type = 0){
       $d = array();
       if($type){
           $p = param_to_str($param);

           $res = post_interface($url, $p);
       }else{
           $res = get_interface($url, $param);
       }
       if($res['contents']){
           $contents = json_decode($res['contents'], true);
           if($contents['code'] == 0){
               if(isset($contents['content'])){
                   $contents = $contents['content'];
                   if($contents['count']){
                       $d['records'] = $contents['count'];
                       $d['rows'] = $contents['data'];
                       $d['total'] = ceil($contents['count'] / $param['rows']);
                       $d['page'] = ($param['offset']/$param['rows']) + 1;
                   }else{
                       if(isset($contents)){
                           $d = $contents;
                       }else{
                           $d = true;
                       }
                   }
               }
           }
       }
       return $d;
   }
   */
    protected function get_data_url_zhyy($url, $param = array(), $type = 0){
        $d = array();
        if($type){
            $p = param_to_str($param);

            $res = post_interface($url, $p);
        }else{
            $res = $this->get_interface($url, $param);
        }
        if($res['contents']){
            $contents = json_decode($res['contents'], true);
            if($contents['code'] == 0){
                $d = $contents['data'];
            }
        }
        return $d;
    }


    /**
     * 远程获取数据(曹笑诚)
     * @param Array $refers refers列表数组(注意：不同refer 有不同的返回字段，多个refer时 注意选择合适的refer参数)
     * @param String or Array $param 参数
     * @param int $type 0 get ; 1 post
     */
    protected function get_data_url_from_cxc($refers=true,  $param = array(), $type = 0){
        $url = URL;

        $p['product'] = 'tai_wan_ma_jiang';

        if($refers === true){
            $refers = array(
                'day_active_user',// 日活
                'day_added_user',// 新增
                'online_user',//在线人数
                'recharge_user',//充值人数
                'recharge_amount',// 充值金额
                'start_room_num',// 开桌数
                'finish_room_num',// 完成桌数
                'start_table_num',// 开局数
                'finish_table_num',// 完成局数
                'added_user_table_num',// 新增局数
            );
        }

        $p['refer'] = json_encode($refers);
        $url = $this->set_url_param($url, $p);

        $d = array();
        if($type){
            $res = post_interface($url, $param);
        }else{
            $res = $this->get_interface($url, $param);
        }

        if($res['contents']){
            $contents = json_decode($res['contents'], true);

            if($contents['status'] = 'success' && $contents['result']){

                $d = $contents['result'];
            }

        }
        return $d;
    }




    /**
     * 远程获取数据(曹笑诚), 并进行格式化， 主要用于按日期统计的数据列表
     * @param Array $refers refers列表数组
     * @param String or Array $param 参数
     * @param int $type 0 get ; 1 post
     */
    protected function get_date_statistic_data($refers=true,  $param = array(), $type = 0){
        $d = $this -> get_data_url_from_cxc($refers, $param, $type);
        $d = $this -> format_data_for_cxc($d);
        return $d;
    }

    protected function get_date_statistic_data1($refers=true,  $param = array(), $type = 0){
        $d = $this -> get_data_url_from_cxc($refers, $param, $type);
        return $d;
    }


    /*
    * 格式化曹笑诚接口数据 (主要用于按日期统计)
    */
    protected function format_data_for_cxc($d){
        $data = array();

        foreach($d as $k => $v){
            if(!isset($data[$v['datetime']])){
                $data[$v['datetime']] = array();
            }
            $data[$v['datetime']]['datetime'] = $v['datetime'];
            switch($v['refer']){
                case 'day_active_user'://日活
                case 'day_added_user'://新增
                case 'online_user'://在线人数
                case 'recharge_user'://充值人数
                case 'recharge_amount'://充值金额
                case 'start_room_num'://开桌数
                case 'finish_room_num'://完成桌数
                case 'start_table_num'://开局数
                case 'finish_table_num'://完成局数
                case 'added_user_table_num'://新增局数
//                case 'finish_match_num'://
//                case 'start_table_num'://
//                case 'finish_table_num'://
//                case 'avg_finish_table'://
//                case 'recharge_diamond_user'://
//                case 'recharge_diamond_amount'://
//                case 'recharge_diamond_num'://
//                    $data[$v['datetime']][$v['refer']] = $v['result'];
//                    break;
//
//
//                case 'login_retention':
//                case 'valid_retention':
//                case 'recharge_retention':
//                    $data[$v['datetime']][$v['refer'] . '_'.$v['retention_days']] = $v['retention_num'];
//                    break;
//
//                case 'recharge_diamond_detail': //售钻详情
//
//                    break;
//
//                case 'game_mode_daily_detail':
//                    $data[$v['datetime']][$v['refer']] = $v['result'];
//                    break;
            }
        }

        $data = array_values($data);
        return $data;
    }


    //解析jqGrid的筛选参数
    protected function parse_search_data(){
        $search_data = I('search_data', null, 'trim');
        $search_time = '';
        $search_arr = array();
        if($search_data){
            $search_arr = parse_param($search_data, true);
            if(!empty($search_arr['search_time'])){
                $search_time = $search_arr['search_time'];
                $times = explode(' - ', $search_time);
                $search_arr['start_date'] = $times[0];
                $search_arr['end_date'] = $times[1];
                unset($search_arr['search_time']);
            }
        }
        return $search_arr;
    }

}